<template>
  <div class="auth-container">
    <el-card class="auth-card" v-show="!data.dialogVisible">
      <div class="auth-header">
        <img src="../../assets/it3.png" alt="Avatar" class="auth-avatar" />
        <h2 class="title">实名认证</h2>
      </div>
      <el-form ref="formRef" :model="user" label-width="100px">
        <el-form-item label="真实姓名：" prop="name">
          <el-input v-model="user.name" :disabled="isDisabled" :placeholder="isEditMode ? '请输入真实姓名' : user.name"
            maxlength="10" />
        </el-form-item>
        <el-form-item label="身份证号：" prop="idCard">
          <el-input v-model="user.idCard" :disabled="isDisabled" maxlength="18" />
          <!-- <span v-if="isDisabled" style="position: fixed; top: 536px; left: 800px;">已认证</span> -->
        </el-form-item>
        <div class="action-buttons">
          <template v-if="!isDisabled">
            <el-button type="primary" @click="submit">提交认证</el-button>
            <el-button @click="resetForm">重置</el-button>
          </template>
        </div>
      </el-form>
    </el-card>

    <el-card class="auth-card" v-show="data.dialogVisible">
      <div>
        <video autoplay playsinline id="player" v-if="data.videoPlay"></video>
        <el-button id="close" style="display: none;">错 误 取 消</el-button>
        <el-row>
          <el-col :span="7"></el-col>
          <el-col :span="10">
            <el-row>
              <el-col :span="12"><el-button type="info" id="snapshot" :disabled="data.makeSure == 2">上 传</el-button></el-col>
              <el-col :span="12"><el-button type="success" :disabled="!data.makeSure == 2" @click="submit">确 定</el-button></el-col>
            </el-row>
          </el-col>
          <el-col :span="7"></el-col>
        </el-row>

        <!-- 身份证正面 身份证反面 -->
        <el-card>
          <el-row>
            <el-col :span="12">
              <span class="btn1" style="cursor: pointer;">身份证正面</span>
              <canvas width="100px" height="50px" id="picture"></canvas>
            </el-col>
            <el-col :span="12">
              <span class="btn2" style="cursor: pointer;">身份证反面</span>
              <canvas width="100px" height="50px" id="right-picture"></canvas>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </el-card>
  </div>

</template>


<script setup>
import { ref, onMounted, nextTick, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo, realNameAuthentication } from '@/api/edit'
import { ReallyName } from '@/api/ReallyName'
import { useUserStore } from '@/stores/user'

nextTick(() => {
  let videoPlay = document.querySelector('#player')
  let snapshot = document.querySelector('#snapshot')
  let close = document.querySelector('#close')
  let open = document.querySelector('#open')
  let btn1 = document.querySelector('.btn1')
  let btn2 = document.querySelector('.btn2')
  let picture = document.querySelector('#picture')
  let right_picture = document.querySelector('#right-picture')
  let mediaStream

  //获取视频数据
  function gotMediaStream(stream) {
    mediaStream = stream;
    videoPlay.srcObject = stream; //将获取到的值赋值给video标签
  }

  function stopMediaStream() {
    if (mediaStream) {
      mediaStream.getTracks().forEach(track => {
        track.stop()
      })
      mediaStream = null; // 清空mediaStream以避免重复停止
    }
  }

  function handleError(err) {
    console.log(err.name + " : " + err.message)
  }

  btn1.addEventListener('click', function () {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      console.log("你的浏览器不支持")
    } else {
      let constrains = {
        video: true,
        audio: false
      }
      navigator.mediaDevices.getUserMedia(constrains)
        .then(gotMediaStream)
        .catch(handleError)
    }
  }, false)

  btn2.addEventListener('click', function () {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      console.log("你的浏览器不支持")
    } else {
      let constrains = {
        video: true,
        audio: false
      }
      navigator.mediaDevices.getUserMedia(constrains)
        .then(gotMediaStream)
        .catch(handleError)
    }
  }, false)

  snapshot.addEventListener('click', function () {
    if (data.control && mediaStream) {
      if (!data.left) {
        right_picture.getContext('2d').drawImage(videoPlay, 0, 0, right_picture.width, right_picture.height)
        data.control = !data.control
        data.videoPlay = !data.videoPlay
        data.makeSure += 1
      }
      if (data.left) {
        data.left = !data.left
        picture.getContext('2d').drawImage(videoPlay, 0, 0, picture.width, picture.height)
        data.makeSure += 1
      }
      close.click()
    }

  }, false)


  close.addEventListener('click', function () {
    stopMediaStream();
    videoPlay.srcObject = null; // 清空video元素的srcObject以停止播放
  }, false)
  // --------------------------------------------------------------------------------------------
})



const isDisabled = ref(false)

const data = reactive({
  dialogVisible: false,  //身份验证的识别对话框
  left: true,
  control: true,
  videoPlay: true,
  makeSure: 0,
})

const user = ref({
  name: '',
  idCard: ''
})
const isEditMode = ref(true)
const formRef = ref(null)

function validateIDCard(idCard) {
  const regex = /^[1-9]\d{5}(19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
  if (!regex.test(idCard)) return false
  const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  const checkDigits = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  let sum = idCard.slice(0, 17).split('').reduce((acc, num, idx) => acc + num * weightFactors[idx], 0)
  const mod = sum % 11
  const checkDigit = checkDigits[mod]
  return checkDigit.toUpperCase() === idCard[17].toUpperCase()
}

const submit = async () => {
  data.dialogVisible = true
  if (!data.left) {
    const flag = validateIDCard(user.value.idCard)
    if (flag) {
      await ReallyName({
        name: user.value.name.trim(),
        idCard: user.value.idCard.toUpperCase()
      }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success('认证成功')
          history.go(-1)
        } else {
          ElMessage.error('认证失败')
        }
      })
    } else {
      ElMessage.info('身份证格式错误')
      data.dialogVisible = false
      user.value.idCard = null
    }
  }
}

const fetchUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    const userObj = useUserStore()
    realNameAuthentication(userObj.user.id).then(res => {
      if (res.data.data.idCard) {
        isDisabled.value = true
      }
    })
    user.value = {
      name: data.data.data.name,
      idCard: data.data.idCard
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

const resetForm = () => {
  formRef.value.resetFields()
}

onMounted(() => {
  fetchUserInfo()
})
</script>



<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 82vh;
  background-color: #f5f5f5;
}

.auth-card {
  max-width: 400px;
  width: 100%;
  padding: 40px;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  position: relative;
}

.auth-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.auth-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

:deep(.el-input__inner) {
  letter-spacing: 0.5px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 5px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #666;
}




#player {
  position: fixed;
  top: 100px;
  width: 360px;
  height: 260px;
}
</style>